<template>
  <div class="schedule-management-detail">
    <!-- 上方展示信息区域 -->
    <div class="header-info">
      <div class="info-left">
        <!-- 需求名称区域 -->
        <div class="requirement-name-container">
          <span class="requirement-name-title">需求名称：</span>
          <span class="requirement-name-value">{{ requirementData.dname || '-' }}</span>
        </div>
        <!-- 其他信息区域 -->
        <div class="additional-info">
          <span class="requirement-no">关联合同：{{ requirementData.coName || '-' }}</span>
          <span class="contract-no">物料内容：{{ requirementData.materialName || '-' }}</span>
          <span class="requirement-no">需求编号：{{ requirementData.dno || '-' }}</span>
        </div>
        <div class="additional-info">
          <span class="requirement-type">生产加工单数：{{ requirementData.productionNumber || 0 }}</span>
          <span class="material-content">完成数量：{{ requirementData.successNumber || 0 }}</span>
          <span class="create-time">排产总数：{{ requirementData.numberSum || 0 }}</span>
        </div>
        <div class="additional-info">
          <span class="creator">销售人员：{{ requirementData.saleName || '-' }}</span>
          <span class="create-time">创建时间：{{ requirementData.createTime || '-' }}</span>
        </div>
      </div>
      <div class="info-right">
        <el-button @click="handleBack" plain>返回</el-button>
      </div>
    </div>

    <!-- 下方使用el-tabs实现页签切换 -->
    <div class="main-content-container">
      <el-tabs v-model="activeTab" style="width: 100%">
        <!-- 生产加工单页签 -->
        <el-tab-pane label="生产加工单" name="production">
          <div class="tab-content">
            <!-- 工具栏 -->
            <div class="toolbar">
              <el-button 
                type="primary" 
                @click="handleBatchEdit"
                :disabled="selectedRows.length === 0"
                style="margin-right: 10px;"
              >
                批量编辑
              </el-button>
              <el-button>批量下载</el-button>
              <!-- <el-button>批量导出</el-button> -->
              <!-- <span class="export-tip">导出时未提供模板,先不做,按钮隐藏</span> -->
            </div>
            
            <!-- 数据表格 -->
            <el-table 
              :loading="orderLoading"
              @selection-change="handleSelectionChange" 
              :data="productionOrderList" 
              style="width: 100%" border
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="wno" label="生产加工单号" align="left" />
              <el-table-column prop="number" label="排产数量" align="left" />
              <el-table-column prop="stateTracking" label="过程跟踪" align="left" />
              <el-table-column prop="" label="开始时间" align="left" />
              <el-table-column prop="" label="完成时间" align="left" />
              <el-table-column label="操作" align="left">
                <template #default="scope">
                  <el-link type="primary" size="small" @click="editSchedule(scope.row)">编辑</el-link>
                  <!-- <el-button type="primary" size="small">编辑</el-button> -->
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <el-pagination
              style="margin-top: 20px; justify-content: flex-end;"
              v-model:current-page="productionQuery.pageNum"
              v-model:page-size="productionQuery.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="productionTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleProductionSizeChange"
              @current-change="handleProductionCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 产品列表页签 -->
        <el-tab-pane label="产品列表" name="product">
          <div class="tab-content">
            <!-- 工具栏 -->
            <div class="toolbar">
              <el-button>批量下载标签</el-button>
            </div>
            
            <!-- 数据表格 -->
            <el-table :loading="productLoading" :data="productList" style="width: 100%" border>
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="pNo" label="产品编号" align="left" />
              <el-table-column prop="wId" label="生产加工单" align="left" />
              <el-table-column prop="status" label="当前状态" align="left">
                <template #default="scope">
                  <span>{{ statusMap[scope.row.status] || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="排产时间" align="left" />
              <el-table-column prop="inBoundTime" label="入库时间" align="left" />
              <el-table-column prop="outBoundTime" label="出库时间" align="left" />
              <el-table-column label="操作" align="left">
                <template #default="scope">
                  <el-link type="primary" @click="handleViewParams(scope.row)">查看参数</el-link>
                  <el-link type="primary" @click="handleViewTags(scope.row)" style="margin-left: 10px;">查看标签</el-link>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <el-pagination
              style="margin-top: 20px; justify-content: flex-end;"
              v-model:current-page="productQuery.pageNum"
              v-model:page-size="productQuery.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="productTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleProductSizeChange"
              @current-change="handleProductCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 需求参数页签 - 左右分布布局 -->
        <el-tab-pane label="需求参数" name="requirement">
          <div class="requirement-layout">
            <!-- 左侧配置内容 -->
            <div class="left-sidebar">
              <h3 class="config-title">配置内容</h3>
              <div class="tab-container">
                <div 
                  class="tab-item" 
                  :class="{ active: requirementTab === 'technical' }"
                  @click="requirementTab = 'technical'"
                >
                  <span class="dot"></span>
                  <span class="tab-text">技术参数</span>
                </div>
                <div 
                  class="tab-item" 
                  :class="{ active: requirementTab === 'business' }"
                  @click="requirementTab = 'business'"
                >
                  <span class="dot"></span>
                  <span class="tab-text">业务参数</span>
                </div>
              </div>
            </div>

            <!-- 右侧内容区域 -->
            <div class="right-content">
              <!-- 技术参数 -->
              <div v-if="requirementTab === 'technical'" class="technical-content">
                <div v-if="requirementData.file" class="excel-preview-container">
                  <h3 class="config-title">技术参数</h3>
                  <VueOfficeExcel
                    :src="requirementData.file"
                    style="width: 100%; height: 500px;"
                  />
                </div>
                <div v-else class="no-file-tip">
                  <el-empty description="暂无技术参数文件"></el-empty>
                </div>
              </div>

              <!-- 业务参数 -->
              <div v-else-if="requirementTab === 'business'" class="business-content">
                <div v-if="parsedBusinessParam" class="business-params-container">
                  <h3 class="config-title">业务参数</h3>
                  <div class="business-item" style="margin-top: 25px;">
                    <div class="business-label">紧急程度：</div>
                    <div class="business-value">{{ parsedBusinessParam.degreeUrgency === 1 ? '紧急' : '一般' }}</div>
                  </div>
                  <div class="business-item">
                    <div class="business-label">交付日期：</div>
                    <div class="business-value">{{ parsedBusinessParam.delivery || '暂无' }}</div>
                  </div>
                  <div class="business-item">
                    <div class="business-label">客户要求：</div>
                    <div class="business-value customer-requirements">
                      {{ parsedBusinessParam.requirements || '暂无' }}
                    </div>
                  </div>
                </div>
                <div v-else class="no-data-tip">
                  <el-empty description="暂无业务参数数据"></el-empty>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 编辑弹窗组件 -->
    <EditProductSchedule
      v-model:visible="editVisible"
      :edit-data="editData"
      :is-batch="isBatchEdit"
      @success="handleEditSuccess"
      @cancel="handleEditCancel"
    />
    <!-- 查看参数组件 -->
    <view-params
      v-model:visible="viewParamsVisible"
      :row-data="viewParamsData"
      @close="handleViewParamsClose"
    />
    
    <!-- 查看标签组件 -->
    <view-tags
      v-model:visible="viewTagsVisible"
      :row-data="viewTagsData"
      @close="handleViewTagsClose"
    />
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed } from 'vue';
import VueOfficeExcel from '@vue-office/excel';
import '@vue-office/excel/lib/index.css';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
// 导入新组件
import ViewParams from './viewParams.vue';
import ViewTags from './viewTags.vue';
import EditProductSchedule from './editProductSchedule.vue'
import {
  getDemandDetail,
  getOrderPage,
  getProductsPage
} from '@/api/production'

const router = useRouter();
const route = useRoute();
// 查询生产加工单列表
const getOrderList = async () => {
  orderLoading.value = true
  getOrderPage(productionQuery).then(res => {
    orderLoading.value = false
    productionOrderList.value = res.data?.list || [];
    productionTotal.value = res.data?.total || 0;
  }).catch(() => {
    productionOrderList.value = [];
    productionTotal.value = 0;
  });
}
// 查询产品列表
const getProductList = async () => {
  productLoading.value = true
  getProductsPage(productQuery).then(res => {
    productLoading.value = false
    productList.value = res.data?.list || [];
    productTotal.value = res.data?.total || 0;
  }).catch(() => {
    productList.value = [];
    productTotal.value = 0;
  });
}
// 监听路由参数变化，更新流程信息
watch(
  () => route.params,
  (newParams) => {
    if (newParams.schedule) {
      getDemandDetail(newParams?.schedule).then(res => {
        if (res.code === 200 && res.data) {
          // 使用Object.assign保留响应性
          Object.assign(requirementData, res.data || {});
          productionQuery.deId = newParams?.schedule || ''
          productionQuery.coId = res.data?.coId || ''
          getOrderList()
          getProductList()
        }
      }).catch(() => {})
    }
  },
  { immediate: true, deep: true }
)

// 活动选项卡
const activeTab = ref('production');
// 需求参数内部选项卡
const requirementTab = ref('technical');
// 需求数据
const requirementData = reactive({});
// 生产加工单列表
const orderLoading = ref(false)
// 生产加工单查询参数和分页信息
const productionQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  deId: '',
  coId: ''
});
// 生产加工单数据
const productionOrderList = ref([]);
const productionTotal = ref(0);

// 产品列表查询参数和分页信息
const productQuery = reactive({
  pageNum: 1,
  pageSize: 10
});
// 产品列表
const productLoading = ref(false)
const productList = ref([]);
const productTotal = ref(0);

// 编辑相关状态
const editVisible = ref(false)
const editData = ref({})
const isBatchEdit = ref(false)
const selectedRows = ref([])

// 查看参数相关
const viewParamsVisible = ref(false);
const viewParamsData = ref({});

// 查看标签相关
const viewTagsVisible = ref(false);
const viewTagsData = ref({});

// 状态翻译
const statusMap = {
  1: '待入库',
  2: '已入库',
  3: '已出库',
  4: '已退货',
}

// 解析业务参数JSON
const parsedBusinessParam = computed(() => {
  try {
    if (requirementData.businessParam) {
      // 如果是字符串则解析，否则直接返回
      if (typeof requirementData.businessParam === 'string') {
        return JSON.parse(requirementData.businessParam);
      }
      return requirementData.businessParam;
    }
    return null;
  } catch (error) {
    console.error('解析业务参数失败:', error);
    return null;
  }
});

// 处理返回按钮点击
const handleBack = () => {
  router.push({
    path: '/production/scheduling',
  });
};

// 处理选择变化
function handleSelectionChange(rows) {
  selectedRows.value = rows
  console.log('selectedRows', selectedRows.value);
}

// 处理编辑
function editSchedule(row) {
  isBatchEdit.value = false
  editData.value = {
    wno: row.requirementNo || '',
    currentStep: ''
  }
  editVisible.value = true
}

// 处理批量编辑
function handleBatchEdit() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要编辑的数据')
    return
  }
  
  isBatchEdit.value = true
  // 合并选中的生产加工单号，用分号分隔
  const wnos = selectedRows.value.map(row => row.wno).join('; ')
  editData.value = {
    wno: wnos,
    currentStep: ''
  }
  editVisible.value = true
}

// 处理编辑成功
function handleEditSuccess(formData) {
  console.log('编辑成功，表单数据:', formData)
  ElMessage.success('编辑成功')
  // 实际项目中这里应该调用API更新数据
}

// 处理编辑取消
function handleEditCancel() {
  editData.value = {}
  isBatchEdit.value = false
}

// 处理查看参数
const handleViewParams = (row) => {
  viewParamsData.value = { ...row };
  viewParamsVisible.value = true;
};

// 处理查看参数关闭
const handleViewParamsClose = () => {
  viewParamsData.value = {};
};

// 处理查看标签
const handleViewTags = (row) => {
  viewTagsData.value = { ...row };
  viewTagsVisible.value = true;
};

// 处理查看标签关闭
const handleViewTagsClose = () => {
  viewTagsData.value = {};
};

// 生产加工单分页处理
const handleProductionSizeChange = (size) => {
  productionQuery.pageSize = size;
  // 实际项目中这里应该重新请求数据
};

const handleProductionCurrentChange = (current) => {
  productionQuery.pageNum = current;
  // 实际项目中这里应该重新请求数据
};

// 产品列表分页处理
const handleProductSizeChange = (size) => {
  productQuery.pageSize = size;
  // 实际项目中这里应该重新请求数据
};

const handleProductCurrentChange = (current) => {
  productQuery.pageNum = current;
  // 实际项目中这里应该重新请求数据
};

</script>

<style scoped>
.schedule-management-detail {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

/* 上方展示信息区域样式 */
.header-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.info-left {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 需求名称容器 */
.requirement-name-container {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.requirement-name-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.requirement-name-value {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

/* 额外信息区域 */
.additional-info {
  display: flex;
  align-items: center;
  gap: 0;
  margin-bottom: 5px;
}

.info-left .requirement-no,
.info-left .requirement-type,
.info-left .creator {
  font-size: 14px;
  color: #606266;
  margin-right: 80px;
  min-width: 300px;
  display: inline-block;
  vertical-align: top;
}

.info-left .contract-no,
.info-left .material-content,
.info-left .create-time {
  font-size: 14px;
  color: #606266;
  margin-right: 80px;
  min-width: 300px;
  display: inline-block;
  vertical-align: top;
}

/* 最后一个元素不设置右边距 */
.info-left .additional-info span:last-child {
  margin-right: 0;
}

.info-right {
  display: flex;
  align-items: flex-start;
}

/* 下方主内容区域样式 */
.main-content-container {
  border-radius: 4px;
  overflow: hidden;
  min-height: 600px;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.export-tip {
  color: #909399;
  font-size: 12px;
}

/* 需求参数左右布局样式 */
.requirement-layout {
  display: flex;
  height: 540px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}

/* 左侧选项卡样式 */
.left-sidebar {
  width: 200px;
  background-color: #f5f7fa;
  padding: 20px 20px 20px 20px;
  display: flex;
  flex-direction: column;
}

.config-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-top: 0;
}

.tab-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.tab-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-item.active {
  background-color: #2457d7;
  color: #fff;
}

.tab-item .dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 10px;
}

.tab-item:not(.active) .dot {
  background-color: #409eff;
}

.tab-item.active .dot {
  background-color: #ccc;
}

.tab-text {
  font-size: 14px;
}

/* 右侧内容区域样式 */
.right-content {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  overflow-y: auto;
}

/* 参数内容样式 */
.parameter-total {
  margin-bottom: 15px;
  font-size: 14px;
  color: #606266;
}

.contract-notice {
  margin-top: 15px;
  font-size: 14px;
  color: #f56c6c;
  text-align: center;
}

/* 移除原来的分页容器样式，使用el-pagination自身的样式 */

.business-content {
  background-color: #ffffff;
  border-radius: 4px;
  min-height: 400px;
}

.business-params-container {
  width: 100%;
}

.business-item {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.business-label {
  width: 100px;
  font-weight: bold;
  color: #606266;
  flex-shrink: 0;
}

.business-value {
  flex: 1;
  color: #303133;
}

.customer-requirements {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  max-height: 200px;
  overflow-y: auto;
}

.no-data-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.excel-preview-container {
  width: 100%;
  height: 100%;
}

.no-file-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}
</style>